package com.zyj.exoplayerdemo

import android.content.Context
import android.util.Log
import com.google.android.exoplayer2.upstream.DataSpec
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource
import com.google.android.exoplayer2.upstream.cache.CacheDataSource
import com.google.android.exoplayer2.upstream.cache.CacheWriter
import java.util.concurrent.Executors

/**
 * @Description: 视频缓存工具类
 * @author: zhaoyj
 * @date: 2022/6/14
 */
object VideoCacheUtil {

    private val work = Executors.newFixedThreadPool(3)

    /**
     * 异步缓存视频
     */
    fun cacheoAsync(
        context: Context,
        dataSpec: DataSpec,
        progressListener: CacheWriter.ProgressListener
    ) {
        work.submit {
            cacheSync(context, dataSpec, progressListener)
        }
    }

    /**
     * 同步缓存视频
     */
    fun cacheSync(
        context: Context,
        dataSpec: DataSpec,
        progressListener: CacheWriter.ProgressListener
    ) {
        runCatching {
            val mHttpDataSourceFactory =
                DefaultHttpDataSource.Factory().setAllowCrossProtocolRedirects(true)

            val mDefaultDataSourceFactory =
                DefaultDataSourceFactory(context, mHttpDataSourceFactory)

            val mCacheDataSource = CacheDataSource.Factory()
                .setCache(MyApp.cache)
                .setUpstreamDataSourceFactory(mDefaultDataSourceFactory)
                .createDataSource()

            CacheWriter(mCacheDataSource, dataSpec, null, progressListener).cache()
        }.onFailure {
            Log.d("zyj-", "VideoCacheUtil ${it.message}")
            it.printStackTrace()
        }
    }

}